package com.sakura.oj.exception;

import com.sakura.oj.common.BaseResponse;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.security.SignatureException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(SignatureException.class)
    public BaseResponse<?> signatureExceptionHandler(SignatureException e) {
        log.error("SignatureException", e);
        return ResultUtils.error(ErrorCode.SIGN_ERROR);
    }


    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    // 处理表单参数校验异常（@RequestParam + @Validated）
    @ExceptionHandler(BindException.class)
    public BaseResponse<?> handleBindException(BindException e) {
        String errorMsg = formatBindErrors(e.getBindingResult());
        log.error("参数绑定异常: {}", errorMsg);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, errorMsg);
    }

    // 处理JSON参数校验异常（@RequestBody + @Validated）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
        String errorMsg = formatBindErrors(e.getBindingResult());
        log.error("参数校验异常: {}", errorMsg);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, errorMsg);
    }

    // 处理单个参数校验异常（@RequestParam单个参数校验）
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse<?> handleConstraintViolation(ConstraintViolationException e) {
        String errorMsg = e.getConstraintViolations().stream()
                .map(v -> {
                    // 提取校验失败的参数名称
                    String path = v.getPropertyPath().toString();
                    return path.substring(path.lastIndexOf(".") + 1) + ": " + v.getMessage();
                })
                .collect(Collectors.joining("; "));
        log.error("参数校验异常: {}", errorMsg);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, errorMsg);
    }

    // 格式化绑定错误信息
    private String formatBindErrors(BindingResult bindingResult) {
        return bindingResult.getFieldErrors().stream()
                .map(fieldError -> {
                    String msg = fieldError.getDefaultMessage();
                    // 如果消息包含校验类型，进行美化处理
                    if (msg != null && msg.startsWith("{javax.validation.constraints")) {
                        return fieldError.getField() + "格式错误";
                    }
                    return fieldError.getField() + ": " + msg;
                })
                .collect(Collectors.joining("; "));
    }
}
